import React, { useState } from 'react'
import {
  Card,
  Button,
  Space,
  Modal,
  Form,
  Input,
  InputNumber,
  Select,
  Switch,
  Tag,
  message,
  Popconfirm,
  Divider,
  Row,
  Col,
  Tree,
  Typography,
  TreeSelect,
  Descriptions,
  Radio
} from 'antd'
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  MenuOutlined,
  LinkOutlined,
  SettingOutlined,
  UserOutlined,
  TeamOutlined,
  ApartmentOutlined,
  DashboardOutlined,
  SafetyCertificateOutlined,
  BookOutlined
} from '@ant-design/icons'

const { Title } = Typography
const { Option } = Select
const { TextArea } = Input

// 菜单类型枚举
const MENU_TYPES = {
  DIRECTORY: 1, // 目录
  MENU: 2, // 菜单
  BUTTON: 3 // 按钮
}

// 图标映射 - 提前定义
const iconComponents = {
  SettingOutlined: <SettingOutlined />,
  UserOutlined: <UserOutlined />,
  TeamOutlined: <TeamOutlined />,
  MenuOutlined: <MenuOutlined />,
  ApartmentOutlined: <ApartmentOutlined />,
  LinkOutlined: <LinkOutlined />,
  DashboardOutlined: <DashboardOutlined />,
  SafetyCertificateOutlined: <SafetyCertificateOutlined />,
  BookOutlined: <BookOutlined />
}

// 常用图标选项
const iconOptions = [
  { value: 'DashboardOutlined', label: '仪表盘' },
  { value: 'UserOutlined', label: '用户' },
  { value: 'TeamOutlined', label: '团队' },
  { value: 'SettingOutlined', label: '设置' },
  { value: 'ApartmentOutlined', label: '组织' },
  { value: 'MenuOutlined', label: '菜单' },
  { value: 'SafetyCertificateOutlined', label: '安全' },
  { value: 'BookOutlined', label: '书籍' },
  { value: 'LinkOutlined', label: '链接' }
]

// 辅助函数 - 提前定义
const getMenuTypeText = type => {
  switch (type) {
    case MENU_TYPES.DIRECTORY:
      return '目录'
    case MENU_TYPES.MENU:
      return '菜单'
    case MENU_TYPES.BUTTON:
      return '按钮'
    default:
      return '未知'
  }
}

const getMenuTypeColor = type => {
  switch (type) {
    case MENU_TYPES.DIRECTORY:
      return 'blue'
    case MENU_TYPES.MENU:
      return 'green'
    case MENU_TYPES.BUTTON:
      return 'orange'
    default:
      return 'default'
  }
}

const getMenuColor = type => {
  switch (type) {
    case MENU_TYPES.DIRECTORY:
      return '#1890ff'
    case MENU_TYPES.MENU:
      return '#52c41a'
    case MENU_TYPES.BUTTON:
      return '#fa8c16'
    default:
      return '#8c8c8c'
  }
}

// 模拟菜单数据
const initialMenus = [
  {
    id: 1,
    name: '系统管理',
    type: MENU_TYPES.DIRECTORY,
    icon: 'SettingOutlined',
    path: '/system',
    sort: 1,
    status: true,
    permission: '',
    component: '',
    external: false,
    createTime: '2023-01-15 10:30:00',
    children: [
      {
        id: 2,
        name: '用户管理',
        type: MENU_TYPES.MENU,
        icon: 'UserOutlined',
        path: '/system/user',
        sort: 1,
        status: true,
        permission: 'system:user',
        component: '@/pages/system/user',
        external: false,
        createTime: '2023-01-16 14:20:00',
        children: [
          {
            id: 3,
            name: '用户新增',
            type: MENU_TYPES.BUTTON,
            icon: '',
            path: '',
            sort: 1,
            status: true,
            permission: 'system:user:add',
            component: '',
            external: false,
            createTime: '2023-01-17 09:15:00'
          },
          {
            id: 4,
            name: '用户编辑',
            type: MENU_TYPES.BUTTON,
            icon: '',
            path: '',
            sort: 2,
            status: true,
            permission: 'system:user:edit',
            component: '',
            external: false,
            createTime: '2023-01-17 10:20:00'
          }
        ]
      },
      {
        id: 5,
        name: '角色管理',
        type: MENU_TYPES.MENU,
        icon: 'TeamOutlined',
        path: '/system/role',
        sort: 2,
        status: true,
        permission: 'system:role',
        component: '@/pages/system/role',
        external: false,
        createTime: '2023-01-18 11:30:00'
      },
      {
        id: 6,
        name: '菜单管理',
        type: MENU_TYPES.MENU,
        icon: 'MenuOutlined',
        path: '/system/menu',
        sort: 3,
        status: true,
        permission: 'system:menu',
        component: '@/pages/system/menu',
        external: false,
        createTime: '2023-01-19 13:45:00'
      }
    ]
  },
  {
    id: 7,
    name: '组织架构',
    type: MENU_TYPES.DIRECTORY,
    icon: 'ApartmentOutlined',
    path: '/organization',
    sort: 2,
    status: true,
    permission: '',
    component: '',
    external: false,
    createTime: '2023-02-01 10:30:00',
    children: [
      {
        id: 8,
        name: '部门管理',
        type: MENU_TYPES.MENU,
        icon: 'ApartmentOutlined',
        path: '/organization/dept',
        sort: 1,
        status: true,
        permission: 'organization:dept',
        component: '@/pages/organization/dept',
        external: false,
        createTime: '2023-02-02 14:20:00'
      }
    ]
  },
  {
    id: 9,
    name: '外部链接',
    type: MENU_TYPES.MENU,
    icon: 'LinkOutlined',
    path: 'https://ant.design',
    sort: 3,
    status: true,
    permission: 'external:link',
    component: '',
    external: true,
    createTime: '2023-02-10 16:30:00'
  }
]

const MenuManagement = () => {
  const [menus, setMenus] = useState(initialMenus)
  const [modalVisible, setModalVisible] = useState(false)
  const [editingMenu, setEditingMenu] = useState(null)
  const [selectedMenu, setSelectedMenu] = useState(null)
  const [expandedKeys, setExpandedKeys] = useState(['1', '2', '7'])
  const [form] = Form.useForm()

  // 转换菜单数据为树形结构
  const convertToTreeData = data => {
    return data.map(item => ({
      key: item.id,
      title: (
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between'
          }}
        >
          <span>
            {item.icon &&
              iconComponents[item.icon] &&
              React.cloneElement(iconComponents[item.icon], {
                style: { marginRight: 8, color: getMenuColor(item.type) }
              })}
            {item.name}
            {item.external && (
              <LinkOutlined style={{ marginLeft: 4, color: '#1890ff' }} />
            )}
          </span>
          <Space size='small'>
            <Tag color={getMenuTypeColor(item.type)} size='small'>
              {getMenuTypeText(item.type)}
            </Tag>
            <Tag color={item.status ? 'green' : 'red'} size='small'>
              {item.status ? '启用' : '停用'}
            </Tag>
          </Space>
        </div>
      ),
      children: item.children ? convertToTreeData(item.children) : [],
      isLeaf:
        item.type === MENU_TYPES.BUTTON ||
        !item.children ||
        item.children.length === 0,
      data: item
    }))
  }

  const treeData = convertToTreeData(menus)

  // 获取所有菜单选项（用于父菜单选择）
  const getMenuOptions = (menuData, level = 0) => {
    let options = []
    menuData.forEach(menu => {
      if (menu.type !== MENU_TYPES.BUTTON) {
        // 按钮不能作为父菜单
        options.push({
          value: menu.id,
          label: `${'─'.repeat(level)} ${menu.name} [${getMenuTypeText(menu.type)}]`,
          disabled: editingMenu && menu.id === editingMenu.id
        })
        if (menu.children) {
          options = [...options, ...getMenuOptions(menu.children, level + 1)]
        }
      }
    })
    return options
  }

  const menuOptions = getMenuOptions(menus)

  // 显示编辑/新增模态框
  const showModal = (menu = null, parentId = null) => {
    setEditingMenu(menu)
    if (menu) {
      form.setFieldsValue({
        ...menu,
        parentId: menu.parentId || 0
      })
    } else {
      form.resetFields()
      form.setFieldsValue({
        parentId: parentId || (selectedMenu ? selectedMenu.id : 0),
        type: MENU_TYPES.MENU,
        sort: 1,
        status: true,
        external: false
      })
    }
    setModalVisible(true)
  }

  // 处理表单提交
  const handleSubmit = values => {
    if (editingMenu) {
      // 编辑菜单
      const updateMenu = menuData => {
        return menuData.map(menu => {
          if (menu.id === editingMenu.id) {
            return { ...menu, ...values }
          }
          if (menu.children) {
            return { ...menu, children: updateMenu(menu.children) }
          }
          return menu
        })
      }
      setMenus(updateMenu(menus))
      message.success('菜单更新成功')
    } else {
      // 新增菜单
      const newMenu = {
        id: Math.max(...getAllMenuIds(menus)) + 1,
        ...values,
        createTime: new Date().toLocaleString(),
        children: values.type === MENU_TYPES.DIRECTORY ? [] : undefined
      }

      const addMenu = (menuData, parentId, newMenu) => {
        return menuData.map(menu => {
          if (menu.id === parentId) {
            return {
              ...menu,
              children: [...(menu.children || []), newMenu]
            }
          }
          if (menu.children) {
            return {
              ...menu,
              children: addMenu(menu.children, parentId, newMenu)
            }
          }
          return menu
        })
      }

      setMenus(addMenu(menus, values.parentId, newMenu))
      message.success('菜单创建成功')
    }
    setModalVisible(false)
  }

  // 获取所有菜单ID
  const getAllMenuIds = menuData => {
    let ids = []
    menuData.forEach(menu => {
      ids.push(menu.id)
      if (menu.children) {
        ids = [...ids, ...getAllMenuIds(menu.children)]
      }
    })
    return ids
  }

  // 删除菜单
  const handleDelete = menuId => {
    const deleteMenu = menuData => {
      return menuData.filter(menu => {
        if (menu.id === menuId) {
          return false
        }
        if (menu.children) {
          menu.children = deleteMenu(menu.children)
        }
        return true
      })
    }
    setMenus(deleteMenu(menus))
    message.success('菜单删除成功')
  }

  // 树节点选择
  const onSelect = (selectedKeys, { node }) => {
    setSelectedMenu(node.data)
  }

  // 树节点展开
  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys)
  }

  // 渲染图标选择器
  const renderIconSelector = () => (
    <Select placeholder='选择图标' allowClear optionLabelProp='label'>
      {iconOptions.map(icon => (
        <Option key={icon.value} value={icon.value} label={icon.label}>
          <Space>
            {iconComponents[icon.value]}
            {icon.label}
          </Space>
        </Option>
      ))}
    </Select>
  )

  return (
    <div className='menu-management'>
      <Row gutter={16}>
        {/* 左侧菜单树 */}
        <Col span={10}>
          <Card>
            <div
              style={{
                marginBottom: 16,
                display: 'flex',
                justifyContent: 'space-between'
              }}
            >
              <Title level={4} style={{ margin: 0 }}>
                <MenuOutlined style={{ marginRight: 12 }} />
                菜单结构
              </Title>
              <Space>
                <Button icon={<PlusOutlined />} onClick={() => showModal()}>
                  新增菜单
                </Button>
                {selectedMenu && (
                  <Button
                    icon={<PlusOutlined />}
                    onClick={() => showModal(null, selectedMenu.id)}
                  >
                    添加子菜单
                  </Button>
                )}
              </Space>
            </div>

            <Tree
              treeData={treeData}
              expandedKeys={expandedKeys}
              selectedKeys={selectedMenu ? [selectedMenu.id] : []}
              onSelect={onSelect}
              onExpand={onExpand}
              defaultExpandAll
              style={{ padding: '8px 0' }}
            />
          </Card>
        </Col>

        {/* 右侧详情和操作 */}
        <Col span={14}>
          <Card>
            {selectedMenu ? (
              <>
                <div
                  style={{
                    marginBottom: 16,
                    display: 'flex',
                    justifyContent: 'space-between'
                  }}
                >
                  <Title level={4} style={{ margin: 0 }}>
                    {selectedMenu.icon &&
                      iconComponents[selectedMenu.icon] &&
                      React.cloneElement(iconComponents[selectedMenu.icon], {
                        style: {
                          marginRight: 12,
                          color: getMenuColor(selectedMenu.type)
                        }
                      })}
                    {selectedMenu.name}
                  </Title>
                  <Space>
                    <Button
                      icon={<EditOutlined />}
                      onClick={() => showModal(selectedMenu)}
                    >
                      编辑
                    </Button>
                    <Popconfirm
                      title='确定要删除这个菜单吗？'
                      onConfirm={() => handleDelete(selectedMenu.id)}
                      okText='确定'
                      cancelText='取消'
                    >
                      <Button icon={<DeleteOutlined />} danger>
                        删除
                      </Button>
                    </Popconfirm>
                  </Space>
                </div>

                <Descriptions bordered column={2}>
                  <Descriptions.Item label='菜单类型'>
                    <Tag color={getMenuTypeColor(selectedMenu.type)}>
                      {getMenuTypeText(selectedMenu.type)}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label='排序'>
                    {selectedMenu.sort}
                  </Descriptions.Item>
                  <Descriptions.Item label='状态'>
                    <Tag color={selectedMenu.status ? 'green' : 'red'}>
                      {selectedMenu.status ? '启用' : '停用'}
                    </Tag>
                  </Descriptions.Item>
                  <Descriptions.Item label='外部链接'>
                    <Tag color={selectedMenu.external ? 'blue' : 'default'}>
                      {selectedMenu.external ? '是' : '否'}
                    </Tag>
                  </Descriptions.Item>
                  {selectedMenu.icon && (
                    <Descriptions.Item label='图标'>
                      <Space>
                        {iconComponents[selectedMenu.icon]}
                        {selectedMenu.icon}
                      </Space>
                    </Descriptions.Item>
                  )}
                  <Descriptions.Item label='路由路径' span={2}>
                    {selectedMenu.path || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label='权限标识' span={2}>
                    {selectedMenu.permission || '-'}
                  </Descriptions.Item>
                  {selectedMenu.component && (
                    <Descriptions.Item label='组件路径' span={2}>
                      {selectedMenu.component}
                    </Descriptions.Item>
                  )}
                  <Descriptions.Item label='创建时间'>
                    {selectedMenu.createTime}
                  </Descriptions.Item>
                </Descriptions>
              </>
            ) : (
              <div
                style={{
                  textAlign: 'center',
                  padding: '40px 0',
                  color: '#999'
                }}
              >
                <MenuOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                <div>请选择左侧的菜单查看详情</div>
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 新增/编辑菜单模态框 */}
      <Modal
        title={editingMenu ? '编辑菜单' : '新增菜单'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={700}
      >
        <Form form={form} layout='vertical' onFinish={handleSubmit}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='name'
                label='菜单名称'
                rules={[{ required: true, message: '请输入菜单名称' }]}
              >
                <Input placeholder='请输入菜单名称' />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name='type'
                label='菜单类型'
                rules={[{ required: true, message: '请选择菜单类型' }]}
              >
                <Radio.Group>
                  <Radio value={MENU_TYPES.DIRECTORY}>目录</Radio>
                  <Radio value={MENU_TYPES.MENU}>菜单</Radio>
                  <Radio value={MENU_TYPES.BUTTON}>按钮</Radio>
                </Radio.Group>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item name='parentId' label='父菜单'>
            <TreeSelect
              treeData={[{ value: 0, label: '根菜单', children: menuOptions }]}
              placeholder='请选择父菜单'
              treeDefaultExpandAll
            />
          </Form.Item>

          <Form.Item name='icon' label='菜单图标'>
            {renderIconSelector()}
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name='sort'
                label='排序'
                rules={[{ required: true, message: '请输入排序号' }]}
              >
                <InputNumber min={1} max={999} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name='status' label='状态' valuePropName='checked'>
                <Switch checkedChildren='启用' unCheckedChildren='停用' />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) =>
              prevValues.type !== currentValues.type ||
              prevValues.external !== currentValues.external
            }
          >
            {({ getFieldValue }) => {
              const menuType = getFieldValue('type')
              const isExternal = getFieldValue('external')

              return (
                <>
                  {menuType !== MENU_TYPES.BUTTON && (
                    <Form.Item
                      name='path'
                      label={isExternal ? '外部链接' : '路由路径'}
                      rules={[
                        {
                          required: menuType !== MENU_TYPES.BUTTON,
                          message: '请输入路径'
                        }
                      ]}
                    >
                      <Input
                        placeholder={
                          isExternal ? '请输入外部链接地址' : '请输入路由路径'
                        }
                      />
                    </Form.Item>
                  )}

                  {menuType === MENU_TYPES.MENU && !isExternal && (
                    <Form.Item name='component' label='组件路径'>
                      <Input placeholder='请输入组件路径，如：@/pages/system/user' />
                    </Form.Item>
                  )}

                  {menuType !== MENU_TYPES.DIRECTORY && (
                    <Form.Item name='permission' label='权限标识'>
                      <Input placeholder='请输入权限标识，如：system:user:add' />
                    </Form.Item>
                  )}

                  {menuType !== MENU_TYPES.BUTTON && (
                    <Form.Item
                      name='external'
                      label='外部链接'
                      valuePropName='checked'
                    >
                      <Switch checkedChildren='外部' unCheckedChildren='内部' />
                    </Form.Item>
                  )}
                </>
              )
            }}
          </Form.Item>

          <Form.Item style={{ textAlign: 'right', marginBottom: 0 }}>
            <Space>
              <Button onClick={() => setModalVisible(false)}>取消</Button>
              <Button type='primary' htmlType='submit'>
                {editingMenu ? '更新' : '创建'}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default MenuManagement
